import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:bruno/bruno.dart';
import 'package:search_people/page/search/cell.dart';
import 'package:search_people/utils/component/list/section.dart';
import '../../bean/search/hot_people.dart';
import '../../bean/search/search_list.dart';
import '../../utils/httputils/net_api.dart';
import '../../utils/storage.dart';
import '../../value/topcolors.dart';
import 'state.dart';

class SearchLogic extends GetxController {
  final SearchState state = SearchState();

  var colorBg = [Color(0xffD53814), Color(0xffEB7C2B), Color(0xffEBA52B)];

  @override
  void onInit() {
    super.onInit();

    for (var element in state.strHis) {
      state.histroyWidget.add(GestureDetector(
        onTap: () {
          state.textEditingController.text = element;
          searchKey(element);
        },
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(4.r))),
          margin: EdgeInsets.only(right: 10.r, bottom: 10.r),
          padding: const EdgeInsets.fromLTRB(15.5, 5.5, 15.5, 7.5),
          child: Text(
            element,
            style: TextStyle(fontSize: 14.sp, color: TopColors.black_66),
          ),
        ),
      ));
    }
  }

  deleteHis(context) {
    BrnDialogManager.showConfirmDialog(context,
        title: "清除记录",
        cancel: '取消',
        confirm: '确定',
        message: "确定有清除历史记录？", onConfirm: () {
      state.strHis.clear();
      SpUtil().remove('his');
      update();
      Get.back();
    }, onCancel: () {
      Get.back();
    });
  }

  //添加搜索记录

  inHis(String key) {
    if (state.strHis.contains(key)) {
      state.histroyWidget.removeAt(state.strHis.indexOf(key));
      state.strHis.remove(key);
    }
    state.strHis.add(key);
    state.histroyWidget.add(
      GestureDetector(
        onTap: () {
          state.textEditingController.text = key;
          searchKey(key);
        },
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(4.r))),
          margin: EdgeInsets.only(right: 10.r, bottom: 10.r),
          padding: EdgeInsets.fromLTRB(15.5, 5.5, 15.5, 7.5),
          child: Text(
            key,
            style: TextStyle(fontSize: 14.sp, color: TopColors.black_66),
          ),
        ),
      ),
    );

    SpUtil().setStr('his', state.strHis.toString());
    update();
  }

  //搜索
  searchKey(String key) async {
    state.keywords = key;
    state.page = 1;
    if (key.isNotEmpty) {
      var resultData =
          await Api.search_list({'current': 1, 'queryStr': key, 'size': 20});
      state.serchList = SearchList.fromJson(resultData.data);
      state.curRecords = state.serchList?.records ?? [];
      setupListData(keys: [''], vals: [state.curRecords]);
    }
  }

  //单选搜索
  searchOption(Map<String, dynamic> args) async {
    state.keywords = args.keys.first;
    Map<String, dynamic> parm = {};
    parm.addAll(args);
    parm['current'] = 1;
    parm['size'] = 20;

    state.page = 1;
    var resultData = await Api.searchOption(parm);
    state.serchList = SearchList.fromJson(resultData.data);
    state.curRecords = state.serchList?.records ?? [];
    setupListData(keys: [''], vals: [state.curRecords]);
  }

  //区域搜索
  void searchCity(String key, String val) async {
    state.keywords = key;
    state.page = 1;
    if (key.isNotEmpty) {
      var resultData = await Api.searchCity({key: val});

      List swData = resultData.data['swLeaders'];
      List szfData = resultData.data['szfLeaders'];
      state.serchList = SearchList()..total = swData.length + szfData.length;
      var sw = swData.map((e) => Records.fromJson(e)).toList();
      var szf = szfData.map((e) => Records.fromJson(e)).toList();
      state.curRecords = szf;
      setupListData(keys: ['市委领导', '市政府领导'], vals: [sw, szf]);
    }
  }

  //加载更多
  loadMore() async {
    if (state.page < state.serchList!.pages!.toInt()) {
      state.page++;
      var resultData = await Api.search_list(
          {'current': state.page, 'queryStr': state.keywords, 'size': 20});
      state.serchList = SearchList.fromJson(resultData.data);
      state.curRecords.addAll(state.serchList!.records!);
      setupListData(keys: [''], vals: [state.serchList!.records!]);
      state.refreshController.loadComplete();
    } else {
      state.refreshController.loadNoData();
    }
  }

  //获取热搜人物
  getHotData() async {
    var resultData = await Api.hot_people();
    List data = resultData.data;
    state.hots = data.map((e) => HotPeople.fromJson(e)).toList();
    update();
  }

  getIndexWidge(int index) {
    switch (index) {
      case 0:
        return Container(
          width: 14.r,
          height: 14.r,
          margin: EdgeInsets.only(left: 3, right: 10),
          decoration: BoxDecoration(
              color: colorBg[0],
              borderRadius: BorderRadius.all(Radius.circular(2))),
          child: Center(
            child: Text(
              (index + 1).toString(),
              style: TextStyle(color: Colors.white, fontSize: 11.sp),
            ),
          ),
        );
      case 1:
        return Container(
          width: 14.r,
          height: 14.r,
          margin: EdgeInsets.only(left: 3, right: 10),
          decoration: BoxDecoration(
              color: colorBg[1],
              borderRadius: BorderRadius.all(Radius.circular(2))),
          child: Center(
            child: Text(
              (index + 1).toString(),
              style: TextStyle(color: Colors.white, fontSize: 11.sp),
            ),
          ),
        );
      case 2:
        return Container(
          width: 14.r,
          height: 14.r,
          margin: EdgeInsets.only(left: 3, right: 10),
          decoration: BoxDecoration(
              color: colorBg[2],
              borderRadius: BorderRadius.all(Radius.circular(2))),
          child: Center(
            child: Text(
              (index + 1).toString(),
              style: TextStyle(color: Colors.white, fontSize: 11.sp),
            ),
          ),
        );
    }

    return Container(
      width: 14.r,
      height: 15.r,
      margin: EdgeInsets.only(left: 3, right: 10),
      child: Center(
        child: Text(
          (index + 1).toString(),
          style: TextStyle(color: TopColors.black_99, fontSize: 12.sp),
        ),
      ),
    );
    ;
  }

  void setupListData({
    required List<String> keys,
    required List<List<Records>> vals,
  }) {
    state.resultList = keys
        .asMap()
        .map(
          (key, value) => MapEntry(
            key,
            SectionModel(
              index: key,
              sectionHeader: value.isEmpty
                  ? null
                  : Container(
                      height: 30.r,
                      alignment: Alignment.centerLeft,
                      padding: EdgeInsets.only(left: 10.r),
                      margin:
                          EdgeInsets.only(left: 12.r, top: 5.r, bottom: 5.r),
                      decoration: BoxDecoration(
                          border: Border(
                        left: BorderSide(
                          color: TopColors.main_color,
                          width: 4.r,
                        ),
                      )),
                      child: RichText(
                          text: TextSpan(
                              text: value,
                              style: TextStyle(
                                  color: TopColors.black_33, fontSize: 14.sp),
                              children: [
                            TextSpan(
                              text: vals[key].length.toString(),
                              style: TextStyle(
                                color: TopColors.redfb,
                                fontSize: 16.sp,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            TextSpan(
                              text: '位',
                              style: TextStyle(
                                  color: TopColors.black_33, fontSize: 14.sp),
                            ),
                          ])),
                    ),
              itemBuilder: (context, index) {
                return SearchResultCell(
                    keywords: state.keywords, md: vals[key][index]);
              },
              items: vals[key],
            ),
          ),
        )
        .values
        .toList();
    update();
  }

  @override
  void onReady() async {
    await getHotData();

    if (Get.parameters['type'] == 'city') {
      Map<String, dynamic> arg = Get.arguments;
      searchCity(arg.keys.first, arg.values.first);
    } else if (Get.arguments != null && Get.arguments is Map<String, dynamic>) {
      Map<String, dynamic> arg = Get.arguments;
      searchOption(arg);
    }

    super.onReady();
  }
}
